package jiandian;

import java.util.ArrayList;
import java.util.List;

/**
 * todo
 *
 * @author: luolidong
 * @create: 2021-07-09 19:57
 * @version: 1.0
 */
public class Demo3 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> list = new ArrayList<>();
        int start = newInterval[0];
        int end = newInterval[1];
        int len = intervals.length;
        int i = 0;
        int startBound = 0, endBound = 0;
        //添加重叠的左侧
        while (i < len && intervals[i][1] < start) {
            list.add(intervals[i]);
            i++;
        }
        //处理重叠部分，将较小值作为左边界
        while (i < len && intervals[i][0] <= end) {
            startBound = Math.min(startBound, intervals[i][0]);
            endBound = Math.max(endBound, intervals[i][1]);
            i++;
        }
        list.add(new int[]{startBound, endBound});
        //处理重叠的右侧
        while (i < len) {
            list.add(intervals[i]);
            i++;
        }

        int[][] ans = new int[list.size()][2];
        for (int j = 0; j < list.size(); j++) {
            ans[j] = list.get(j);
        }
        return ans;
    }

    public static void main(String[] args) {

    }
}
